<template>
  <!-- 城市首字母 -->
  <div v-show="showCity" class="c-flex-column c-aligni-center c-ww36 c-pa list-wrapper">
    <div v-for="item of letters" :key="item" :ref="item" class="c-flex-row c-flex-center item" :class="letter == item ? 'booking-tag-selected c-brp50 c-fc-white' : ''" @touchstart="handleTouchStart" @touchmove="handleTouchMove" @touchend="handleTouchEnd" @click="handleLetterClick">{{item}}</div>
  </div>
</template>

<script>
export default {
  name: 'CityAlphabet',
  props: {
    cities: Object,
    letter: {
      type: String,
      default: 'A'
    },
    showCity: {
      type: Boolean,
      default: true
    },
  },
  data() {
    return {
      touchStatus: false,
      startY: 0,
      timeer: null,
    }
  },
  computed: {
    letters() {
      const letters = []
      for (let item of this.cities) {
        letters.push(item.name)
      }
      return letters
    }
  },
  // 生命周期函数
  updated() {
    this.startY = this.$refs['A'][0].offsetTop // A字母距离滚动条顶部距离
  },
  watch: {
  },
  methods: {
    handleLetterClick(e) {
      this.$emit('change', e.target.innerText)
      this.letter = e.target.innerText;
    },
    handleTouchStart(e) {
      this.touchStatus = true;
      this.$emit('change', e.target.innerText)
      this.letter = e.target.innerText;
    },
    handleTouchMove(e) {
      if (this.touchStatus) {
        if (this.timeer) {
          clearTimeout(this.timeer)
        }
        this.timeer = setTimeout(() => {
          const touchY = e.touches[0].clientY - 142 // 手指触摸当前位置距离视口顶部的距离减去142（142指滚动区域最上边和页面顶部之间的距离）
          const index = Math.floor((touchY - this.startY) / 18) // 手指触摸当前位置所在的字母索引（18指单个字母的高度）
          this.letter = this.letters[index];
          if (index >= 0 && index < this.letters.length) {
            this.$emit('change', this.letters[index])
          }
        }, 16)
      }
    },
    handleTouchEnd() {
      this.touchStatus = false
    }
  }
}
</script>

<style scoped>
.list {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  position: absolute;
  right: 0;
  top: 40px;
  bottom: 0;
  width: 30px;
  list-style: none;
  background: rgba(0, 0, 0, 0.2);
  margin: 0;
  padding: 0;
  z-index: 999;
}
.item {
  width: 18px;
  height: 18px;
  font-size: 14px;
}
.list-wrapper {
  top: 12px;
  right: 10px;
}
.booking-tag-selected {
  background-color: #5491ff;
}
</style>
